package com.uni.crawl.job;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.uni.crawl.common.enums.crawl.CrawlInstanceStatusEnum;
import com.uni.crawl.common.enums.crawl.CrawlQueueStatusEnum;
import com.uni.crawl.common.enums.crawl.CrawlQueueUrlTypeEnum;
import com.uni.crawl.model.entity.crawl.CrawlInstance;
import com.uni.crawl.model.entity.crawl.CrawlQueue;
import com.uni.crawl.model.entity.crawl.CrawlTemplate;
import com.uni.crawl.service.crawl.CrawlInstanceService;
import com.uni.crawl.service.crawl.CrawlQueueService;
import com.uni.crawl.service.crawl.CrawlTemplateService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
@AllArgsConstructor
public class CrawlQueueGenerateJob extends AbstractJob {

    protected final CrawlTemplateService crawlTemplateService;
    private final CrawlInstanceService crawlInstanceService;
    private final CrawlQueueService crawlQueueService;

    @XxlJob("crawlQueueGenerateJob")
    @Override
    public ReturnT<String> handle() {
        List<CrawlInstance> insList = crawlInstanceService.list(CrawlInstanceStatusEnum.INIT);
        log.info("need enqueue size = {}", insList.size());
        for (CrawlInstance ins : insList) {
            CrawlTemplate tmpl = crawlTemplateService.getByTmplCode(ins.getTmplCode());
            CrawlQueue queue = BeanUtil.toBean(ins, CrawlQueue.class);
            queue.setId(null);
            queue.setCreateTime(LocalDateTime.now());
            queue.setUpdateTime(null);

            queue.setInstanceId(ins.getId());
            queue.setUrl(tmpl.getSeedUrl());
            queue.setUrlMd5(DigestUtil.md5Hex(queue.getUrl()));
            queue.setUrlType(BooleanUtil.isTrue(tmpl.getPageable()) ?
                    CrawlQueueUrlTypeEnum.LIST.getType() : CrawlQueueUrlTypeEnum.DETAIL.getType());
            queue.setCrawlStatus(CrawlQueueStatusEnum.INIT.getStatus());

            log.info("enqueue tmplCode = {}, instanceId = {}, url = {}", queue.getTmplCode(), queue.getInstanceId(), tmpl.getSeedUrl());
            crawlQueueService.save(queue);

            ins.setInstanceStatus(CrawlInstanceStatusEnum.PROCESSING.getStatus());
            ins.setStartTime(LocalDateTime.now());
            crawlInstanceService.updateById(ins);
        }
        return success();
    }
}
